"""Authentication endpoints - 极简版本."""

from __future__ import annotations

from fastapi import APIRouter, Depends, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_current_user, get_db
from app.models.user import User
from app.schemas.auth import Message, PasswordResetDirect, TokenPair, TokenRefreshRequest
from app.schemas.user import UserCreate, UserOut, UserUpdate
from app.services.auth_service import AuthService

router = APIRouter()


@router.post("/login", response_model=TokenPair, response_model_by_alias=True)
async def login(
    form_data: OAuth2PasswordRequestForm = Depends(),
    session: AsyncSession = Depends(get_db),
) -> TokenPair:
    """用户登录(支持邮箱或用户名).

    Note: Transaction commit is handled by get_db dependency.
    """
    service = AuthService(session)
    tokens = await service.authenticate(form_data.username, form_data.password)
    return TokenPair(
        access_token=tokens.access_token,
        refresh_token=tokens.refresh_token,
        expires_at=tokens.expires_at,
    )


@router.post("/register", response_model=UserOut, status_code=status.HTTP_201_CREATED)
async def register(
    payload: UserCreate,
    session: AsyncSession = Depends(get_db),
) -> UserOut:
    """用户注册.

    Note: Transaction commit is handled by get_db dependency.
    """
    service = AuthService(session)
    user = await service.register(payload)
    return UserOut.model_validate(user)


@router.post("/refresh", response_model=TokenPair, response_model_by_alias=True)
async def refresh_token(
    payload: TokenRefreshRequest,
    session: AsyncSession = Depends(get_db),
) -> TokenPair:
    """刷新访问令牌.

    Note: Transaction commit is handled by get_db dependency.
    """
    service = AuthService(session)
    tokens = await service.refresh(payload.refresh_token)
    return TokenPair(
        access_token=tokens.access_token,
        refresh_token=tokens.refresh_token,
        expires_at=tokens.expires_at,
    )


@router.post("/reset-password-direct", response_model=Message)
async def reset_password_direct(
    payload: PasswordResetDirect,
    session: AsyncSession = Depends(get_db),
) -> Message:
    """直接重置密码(无需邮件验证).

    Note: Transaction commit is handled by get_db dependency.
    """
    service = AuthService(session)
    await service.reset_password_direct(
        email=payload.email, new_password=payload.new_password, confirm_password=payload.confirm_password
    )
    return Message(message="Password reset successfully.")


@router.get("/me", response_model=UserOut)
async def read_current_user(current_user: User = Depends(get_current_user)) -> UserOut:
    """Get current logged-in user information."""
    return UserOut.model_validate(current_user)


@router.put("/me", response_model=UserOut)
async def update_current_user(
    payload: UserUpdate,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_db),
) -> UserOut:
    """Update current user's profile.

    Allows updating:
    - email (must be unique)
    - full_name
    - password (will be hashed)

    Note: is_active, is_admin, and role cannot be updated by users themselves.
    """
    service = AuthService(session)
    updated_user = await service.update_current_user(current_user, payload)
    return UserOut.model_validate(updated_user)
